package com.example.performance.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.performance.mapper.OcrCountMapper;
import com.example.performance.pojo.OcrCount;
import com.example.performance.service.PerformanceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 杨胖胖
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
public class PerformanceServiceImpl implements PerformanceService {

    private final OcrCountMapper mapper;

    private final StringRedisTemplate redisTemplate;

    @Override
    public Map<String, String> urlParamAdd(OcrCount ocrCount) {
        return insertUtils(ocrCount);
    }

    @Override
    public Map<String, String> bodyParamAdd(OcrCount ocrCount) {
        return insertUtils(ocrCount);
    }

    @Override
    public Map<String, String> urlPathParamAdd(OcrCount ocrCount) {
        return insertUtils(ocrCount);
    }

    @Override
    public Map<String, String> formParamAdd(OcrCount ocrCount) {
        return insertUtils(ocrCount);
    }

    @Override
    public OcrCount queryById(String id) {
        String key = "ocr";
        String ocr = redisTemplate.opsForValue().get(key);
        if (ocr == null) {
            OcrCount ocrCount = mapper.queryById(id);
            if (ocrCount != null) {
                redisTemplate.opsForValue().set(key, JSON.toJSONString(ocrCount), 180, TimeUnit.SECONDS);
                return ocrCount;
            }
            return null;
        }
        return JSON.parseObject(ocr, OcrCount.class);
    }

    @Override
    public List<OcrCount> queryByModel(String model) {
        return mapper.queryByModel(model);
    }

    @Override
    public List<OcrCount> queryByModelAndStatus(String model, String status) {
        return mapper.queryByModelAndStatus("%" + model + "%", status);
    }

    /**
     * 插入数据通用方法
     *
     * @param ocrCount 插入的对象
     * @return 返回结果
     */
    public Map<String, String> insertUtils(OcrCount ocrCount) {
        int insert = mapper.insert(ocrCount);
        if (insert == 0) {
            throw new RuntimeException("写入失败");
        }
        log.info("查询写入的内容{}", mapper.selectById(31));
        Map<String, String> response = new HashMap<>();
        response.put("msg", "success");
        return response;
    }
}
